import { defineStore } from 'pinia'

import {
  getCategory1List,
  getCategory2List,
  getCategory3List,
} from '@/api/product/category'
import type { DefineCategoryType } from '@/components/CategorySelector/model'

const initState = {
  category1Id: undefined,
  category2Id: undefined,
  category3Id: undefined,
  category1List: [],
  category2List: [],
  category3List: [],
}
export const useCategoryId = defineStore('category', {
  state: (): DefineCategoryType => initState,
  actions: {
    // 请求一级分类列表数据
    async reqCategory1List() {
      this.category1List = await getCategory1List()
    },

    // 获取二级分类数据
    async reqCategory2List(value: number) {
      if (this.category1Id === value) return
      this.category1Id = value

      this.category2List = await getCategory2List(this.category1Id)
      this.category2Id = undefined
      this.category3Id = undefined
      this.category3List = []
    },

    // 获取三级分类得数据
    async reqCategory3List(value: number) {
      if (this.category2Id === value) return
      this.category2Id = value
      this.category3Id = undefined
      this.category3List = await getCategory3List(this.category2Id)
    },
  },
})
